<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\service;


use app\api\logic\ChapterLogic;
use app\api\logic\PromotionLinkLogic;
use app\common\logic\BaseLogic;
use app\common\model\book\Book;
use app\common\model\buy\EgoldLog;
use app\common\model\Config;
use app\common\model\promotion\PromotionLink;
use app\common\model\user\User as UserModel;
use app\common\model\buy\EgoldCountLog as EgoldCountLogModel;
use app\common\model\buy\EgoldLog as EgoldLogModel;
use app\common\model\buy\BookAutobuy as BookAutobuyModel;


class BuyService extends BaseLogic
{

    /**
     * 是否购买
     *
     * @param $user
     * @param int $book_id
     * @param int $chapter_id
     * @return bool
     */
    public static function isBuy($user, int $book_id, int $chapter_id)
    {
        $userId = $user['id'] ?? 0;

        if (!$userId) {

            return false;
        }
        // 月/季/年会员  在时间内
        if ($user['is_vip'] > 0 && $user['vip_enddate'] > time()) {

            return true;
        }


        //是否已经买过了
        $order = EgoldLogModel::EgoldLogQuery($userId)->where(array('user_id' => $userId, 'book_id' => $book_id, 'chapter_id' => $chapter_id, 'type' => 3))->value('id');

        return $order ? true : false;
    }


    //获取章节售价 pricetype  1：千字 2：章节
    //判断书籍是否单独设置售价，如果不是就用系统售价，如果是就用单独售价，如果单独售价为0，显示系统售价
    public static function getSalePrice($bookinfo, $chapterinfo,$promotion_link_id)
    {
        $promotionLink = PromotionLinkLogic::getPromotionLinkById($promotion_link_id);
        //判断是否为推广链售价
        if(!$promotionLink->isEmpty()){
            if ($promotionLink->paytype == 1) {
                $saleprice = round($chapterinfo->word_count/ 1000 * $promotionLink->egold);
            } else {
                $saleprice = $promotionLink->egold;
            }
        }else{
            if ($bookinfo->pricetype == 1) {
//                $saleprice = $chapterinfo['price'];
//                if ($saleprice <= 0) {
                    $saleprice = round($chapterinfo->word_count / 1000 * $bookinfo->thousand_word_price);
//                }
            } else {
//                $saleprice = $chapterinfo['chapterprice'];
//                if ($saleprice <= 0) {
                    $saleprice = $bookinfo->chapter_price;
//                }
            }
        }


        return $saleprice;
    }

    /**
     * deal_cartoon_buy [购买流程]
     *
     * @param type $user [用户]
     * @param type $bookinfo [小说信息]
     * @param type $chapterinfo [章节信息]
     * @param type $from [来源 1快应用 2手机端]
     * @return type
     **/
    public static function buy($user, $bookinfo, $chapterinfo)
    {
        $user_id = $user['id'];
        //是否VIP章节
        if ($chapterinfo['is_vip'] == 0) {
            return true;
        }

        if (self::isBuy($user, $bookinfo['id'], $chapterinfo['chapter_id'])) {
            return true;
        }
        //月/季/年会员  在时间内
        if ($user['is_vip'] > 0 && $user['vip_enddate'] > time()) {
            return true;
        }

        $saleprice = self::getSalePrice($bookinfo, $chapterinfo,$user->promotion_link_id);
        $egold     = 0;
        $zb        = 0;
        //金币数量是否够用
        if (($user['egold'] + $user['zb']) >= $saleprice) {
            if ($user['paynum'] == 0) {
                ChapterLogic::setError('赠送书币需要先充值才能使用');
                return false;
            }

            try {
                //先消费赠币的情况下
                if (($user['zb']) >= $saleprice) {
                    $zb = $saleprice;
                    self::setEgoldCountLog($user_id, $saleprice);
//                    UserModel::where('id', $user_id)->dec('zb', $saleprice)->update();
                    $buytype = 4;
                } else {
                    //修改用户金币
                    if ($user['zb'] > 0) {
//                        UserModel::where('id', $user_id)->update(['zb' => 0]);
                        self::setEgoldCountLog($user_id, $user['zb']);
                        $egold   = $saleprice - $user['zb'];
                        $zb      = $user['zb'];
                        $buytype = 6;
                        UserModel::where('id', $user_id)->dec('egold', $egold)->update();
                    } else {
                        $egold   = $saleprice;
                        $buytype = 1;
                        UserModel::where('id', $user_id)->dec('egold', $saleprice)->update();
                    }
                }
                //书币记录
                self::egoldlog($user['id'], $bookinfo, $chapterinfo, 3, $buytype, $saleprice, $egold, $zb);
                return true;
            } catch (\Exception $e) {
                ChapterLogic::setError('购买失败');
                return false;
            }
        }
        ChapterLogic::setError('书币余额不足');
        return false;

    }

    //书币记录
    public static function egoldlog($user_id, $bookinfo, $chapterinfo, $type, $buytype = 0, $egold = 0, $used_egold = 0, $zb = 0)
    {
        $osale = [
            'user_id'      => $user_id,
            'type'         => $type,
            'title'        => '订阅：第' . $chapterinfo['chapter_order'] . '章 ' . $bookinfo['book_name'],
            'book_id'      => $bookinfo['id'] ?? 0,
            'book_name'    => $bookinfo['book_name'] ?? null,
            'chapter_name' => $chapterinfo['chapter_name'] ?? null,
            'chapter_id'   => $chapterinfo['chapter_id'] ?? 0,
            'egold'        => $egold,
            'buytype'      => $buytype,
            'used_egold'   => $used_egold,
            'zb'           => $zb,
            'create_time'  => time(),
            'update_time'  => time()
        ];
        EgoldLogModel::EgoldLogQuery($user_id)->insert($osale);
        if ($used_egold > 0) {
            if ($buytype == 1 || $buytype == 6) {//阅读币消费才统计
                //总销售数
                Book::where('id', $bookinfo['id'])->inc('allsellnum', $used_egold)->update();
            }
        }
    }

    public static function autobuy($user_id, $book_id)
    {
        $autobuy = BookAutobuyModel::where(["user_id" => $user_id, "book_id" => $book_id, 'status' => 1])->count();
        if ($autobuy > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    public static function addautobuy($user_id, $book_id,$status)
    {
        $autobuy = BookAutobuyModel::where(["book_id" => $book_id, "user_id" => $user_id])->field('id,status')->find();
        if ($autobuy) {
            BookAutobuyModel::where('id', $autobuy['id'])->update(['status' => $status, 'update_time' => time()]);
        } else {
            $param = array(
                'user_id'   => $user_id,
                'book_id'   => $book_id,
                'status'    => $status,
            );
            BookAutobuyModel::create($param);
        }
        return true;
    }

    /******更新赠币统计记录*****/
    public static function setEgoldCountLog($user_id, $saleprice)
    {
        $score = EgoldCountLogModel::EgoldCountLogQuery($user_id)->where("user_id = $user_id and expire_time>" . strtotime(date('Y-m-d')))->where('delete_time', 0)->order('expire_time ASC')->select();
        if ($score) {
            $time     = time();
            $sumPoint = 0;
            //保存要更新的recordId
            $recordIds = array();
            //目标记录
            $targetRecord = array();
            foreach ($score as $k => $v) {
                //累加，直到值大于等于$saleprice
                $sumPoint += $v['egold'];
                if ($sumPoint >= $saleprice) {
                    $targetRecord = $v;
                    break;
                }
                //记录相应的id值
                $recordIds[] = $v['id'];
            }
            if ($sumPoint < $saleprice) {
                //当前积分不足以消耗
                EgoldCountLogModel::EgoldCountLogQuery($user_id)->where('user_id', $user_id)->save(['delete_time' => $time]);
            } elseif ($sumPoint == $saleprice) {
                //加上最后一条记录的值后，总额刚好等于使用额度
                $recordIds[] = $targetRecord['id'];
            } else {
                $recordIds[] = $targetRecord['id'];
                // 加上最后一条记录的值后，总额刚好大于使用额度，此时需要将最后一条记录拆成两条记录
                $leftPoint = $sumPoint - $saleprice;
                $usePoint  = $targetRecord['egold'] - $leftPoint;

                //添加一条记录
                $point = array(
                    'user_id'      => $targetRecord['user_id'],
                    'egold_log_id' => $targetRecord['egold_log_id'],
                    'egold'        => $leftPoint,
                    'create_time'  => strtotime($targetRecord['create_time']),
                    'expire_time'  => $targetRecord['expire_time']
                );
                EgoldCountLogModel::EgoldCountLogQuery($user_id)->insert($point);
                //修改最后一条记录的积分值
                EgoldCountLogModel::EgoldCountLogQuery($user_id)->where('id=' . $targetRecord['id'])->save(['egold' => $usePoint]);

            }
            //按id删除记录
            if ($recordIds) {
                $map   = [];
                $map[] = ['id', 'in', array_unique($recordIds)];
                EgoldCountLogModel::EgoldCountLogQuery($user_id)->where($map)->save(['delete_time' => $time]);
            }
        }
    }

    public static function obtainEgold($user_id, $egold, $title, $type)
    {
        $time               = time();
        $period_of_validity = Config::where('name', 'period_of_validity')->value('value');//获取后台配置的过期天数
        // 给予用户奖励
//        UserModel::where(['id' => $user_id])->inc('zb', $egold)->update();
        $expire_time        = strtotime(date('Y-m-d', strtotime('+' . $period_of_validity . ' day')));
        $log['user_id']     = $user_id;
        $log['type']        = $type;
        $log['title']       = $title;
        $log['egold']       = $egold;
        $log['create_time'] = $time;
        $log['update_time'] = $time;
        $log['expire_time'] = $expire_time;
        $egoldLogId         = EgoldLogModel::EgoldLogQuery($user_id)->insertGetId($log);
        $data               = [
            'user_id'      => $user_id,
            'egold'        => $egold,
            'egold_log_id' => $egoldLogId,
            'create_time'  => $time,
            'expire_time'  => $expire_time,
            'delete_time'  => 0,
        ];
        EgoldCountLogModel::EgoldCountLogQuery($user_id)->insert($data);
    }
    //获取用户赠币
    public static function getUserZb($user_id)
    {
        $time = time();
        return EgoldCountLogModel::EgoldCountLogQuery($user_id)->where('user_id',$user_id)->where('delete_time','=',0)->where('expire_time','>',$time)->sum('egold');
    }
    //获取用户总充值书币数
    public static function getTotalUserEgold($user_id)
    {
        return EgoldLog::EgoldLogQuery($user_id)->where(['user_id'=>$user_id,'type'=>1])->sum('egold');
    }

}
